package common.system;

import java.io.IOException;
import java.io.InputStream;

public class ProcessRunner implements Runnable
{

	private String command;
	private Process process;
	private StringBuilder outputStream;
	private StringBuilder errorStream;
	private int exitCode;

	public ProcessRunner(String command)
	{
		super();
		this.command = command;
		outputStream = new StringBuilder();
		errorStream = new StringBuilder();
	}

	@Override
	public void run()
	{
		try
		{
			process = Runtime.getRuntime().exec(command);
			readOutput();
			readError();
			//exitCode = (errorStream.length() > 0) ? 1 : 0; 
			exitCode = process.waitFor();
		}
		catch (IOException e)
		{
			exitCode = -1;
			errorStream.append(e.toString());
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}

	private void readOutput()
	{
		int ch;
		InputStream stream = process.getInputStream();
		try
		{
			while ((ch = stream.read()) != -1)
			{
				synchronized (this)
				{
					outputStream.append((char) ch);
				}
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	private void readError()
	{
		int ch;
		InputStream stream = process.getErrorStream();
		try
		{
			while ((ch = stream.read()) != -1)
			{
				synchronized (this)
				{
					errorStream.append((char) ch);
				}
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public String getOutput()
	{
		synchronized (this)
		{
			return outputStream.toString();
		}
	}

	public String getError()
	{
		synchronized (this)
		{
			return errorStream.toString();
		}
	}

	public int getExitCode()
	{
		return exitCode;
	}
}
